{% extends 'base.html' %}
{% load custom_filters %}

{% block title %}教师仪表盘 - 学生管理系统{% endblock title %}

{% block content %}
<div class="container mt-4">
    {% if no_classes %}
    <div class="text-center py-10">
        <div class="bg-warning/10 rounded-lg p-6 inline-block mb-4">
            <i class="bi bi-exclamation-circle fs-4 text-warning"></i>
        </div>
        <h3 class="text-gray-700 mb-2">暂无班级数据</h3>
        <p class="text-gray-500 max-w-md mx-auto">您目前未被分配任何班级，请联系管理员获取班级权限或创建新班级。</p>
    </div>
    {% else %}
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>教师仪表盘</h2>
        <div class="text-right">
            <p class="text-gray-600">{% now "Y年m月d日 l" %}</p>
        </div>
    </div>

    <!-- 统计卡片行 -->
    <div class="row mb-6">
        <div class="col-md-3 mb-1">
            <div class="card bg-primary text-white h-100">
                <div class="card-body p-1">
                    <h5 class="card-title fs-7">班级数量</h5>
                    <p class="card-text fs-4">{{ teacher_classes.count|default:'0' }}</p>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-1">
            <div class="card bg-success text-white h-100">
                <div class="card-body p-1">
                    <h5 class="card-title fs-7">学生总数</h5>
                    <p class="card-text fs-4">{{ total_students|default:'0' }}</p>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-3">
            <div class="card bg-warning text-dark h-100">
                <div class="card-body p-2">
                    <h5 class="card-title fs-6">未提交作业</h5>
                    <p class="card-text display-5">{{ total_unsubmitted_homeworks|default:'0' }}</p>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-3">
            <div class="card bg-info text-white h-100">
                <div class="card-body p-2">
                    <h5 class="card-title fs-6">最近7天考勤</h5>
                    <button class="btn btn-white text-info font-bold btn-xs p-1" onclick="scrollToChart('attendanceChart')">查看图表</button>
                </div>
            </div>
        </div>
    </div>

   

    <!-- 图表和数据行 -->
    <div class="row mb-6">
        <div class="col-lg-6 mb-6">
            <div class="card h-100 shadow-sm border-0">
                <div class="card-header bg-white border-bottom-0">
                    <h5 class="card-title text-gray-800">最近7天考勤统计</h5>
                </div>
                <div class="card-body p-5">
                    <canvas id="attendanceChart" height="300"></canvas>
                </div>
            </div>
        </div>
        <div class="col-lg-6 mb-6">
            <div class="card h-100 shadow-sm border-0">
                <div class="card-header bg-white border-bottom-0">
                    <h5 class="card-title text-gray-800">未交作业统计</h5>
                </div>
                <div class="card-body p-5">
                    <canvas id="homeworkChart" height="300"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- 班级列表 -->
    <div class="card shadow-sm border-0 mb-6">
        <div class="card-header bg-white border-bottom-0">
            <div class="d-flex justify-content-between align-items-center">
                <h5 class="card-title text-gray-800">所带班级</h5>
                <span class="badge bg-primary text-white">{{ teacher_classes.count }} 个班级</span>
            </div>
        </div>
        <div class="card-body p-5">
            <div class="table-responsive">
                <table class="table table-hover table-striped">
                    <thead>
                        <tr class="text-gray-700">
                            <th>班级名称</th>
                            <th>学生数量</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for class in teacher_classes %}
                        <tr class="transition-transform hover:scale-[1.01]">
                            <td>{{ class.grade }} {{ class.name }}</td>
                            <td>{{ class_student_counts|get_item:class.id }}</td>
                            <td>
                                <a href="#" class="btn btn-sm btn-primary shadow-sm hover:bg-primary/90 transition-colors">查看详情</a>
                            </td>
                        </tr>
                        {% empty %}
                        <tr>
                            <td colspan="3" class="text-center text-gray-500 py-5">暂无班级数据</td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

{% endif %}
{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<!-- 调试信息 -->
<script type="text/javascript">
    console.log('考勤标签:', {{ attendance_labels|safe }});
    console.log('出勤数据:', {{ present_data|safe }});
    console.log('缺勤数据:', {{ absent_data|safe }});
    console.log('作业标签:', {{ homework_labels|safe }});
    console.log('作业数据:', {{ homework_data|safe }});
</script>

<script>
    // 平滑滚动到图表
    function scrollToChart(chartId) {
        const chartElement = document.getElementById(chartId);
        if (chartElement) {
            chartElement.scrollIntoView({ behavior: 'smooth' });
        }
    }

    // 增强的图表数据调试
    console.log('===== 图表数据调试信息 =====');
    console.log('考勤标签类型:', typeof {{ attendance_labels|safe }});
    console.log('考勤标签长度:', {{ attendance_labels|safe }}.length);
    console.log('考勤标签内容:', {{ attendance_labels|safe }});
    console.log('出勤数据类型:', typeof {{ present_data|safe }});
    console.log('出勤数据长度:', {{ present_data|safe }}.length);
    console.log('出勤数据内容:', {{ present_data|safe }});
    console.log('缺勤数据类型:', typeof {{ absent_data|safe }});
    console.log('缺勤数据长度:', {{ absent_data|safe }}.length);
    console.log('缺勤数据内容:', {{ absent_data|safe }});
    console.log('作业标签类型:', typeof {{ homework_labels|safe }});
    console.log('作业标签长度:', {{ homework_labels|safe }}.length);
    console.log('作业标签内容:', {{ homework_labels|safe }});
    console.log('作业数据类型:', typeof {{ homework_data|safe }});
    console.log('作业数据长度:', {{ homework_data|safe }}.length);
    console.log('作业数据内容:', {{ homework_data|safe }});
    console.log('============================');

    $(document).ready(function() {
        console.log('页面加载完成，开始初始化图表...');

        // 检查Chart.js是否加载成功
        if (typeof Chart === 'undefined') {
            console.error('Chart.js库未加载成功');
            $('.card-body:has(canvas)').html('<div class="text-center text-danger py-5"><i class="bi bi-exclamation-triangle fs-3 mb-2"></i><p>图表库加载失败，请检查网络连接后刷新页面</p></div>');
            return;
        }

        // 数据清理和解析的工具函数
        const cleanAndParseJson = function(elementId) {
            try {
                const $element = $(`#${elementId}`);
                if (!$element.length) {
                    console.error(`元素 ${elementId} 不存在`);
                    return [];
                }
                let text = $element.text().trim();
                
                // 移除零宽字符和不可见字符
                text = text.replace(/[\u200B-\u200D\uFEFF]/g, '');
                // 安全地解码HTML实体并清理文本
                text = $('<div>').text(text).html().replace(/<[^>]+>/g, '').trim();
                
                text = decodeURIComponent(escape(text));
                const parsedData = JSON.parse(text);
                console.log(`成功解析 ${elementId} 数据:`, parsedData);
                return parsedData;
            } catch (e) {
                console.error(`解析 ${elementId} 数据失败:`, e);
                console.error(`原始 ${elementId} 数据:`, $(`#${elementId}`)?.text());
                return [];
            }
        };

        try {
                // 直接嵌入JSON数据并定义为全局变量
                window.attendanceLabels = {{ attendance_labels|safe }};
                window.presentData = {{ present_data|safe }};
                window.absentData = {{ absent_data|safe }};
                window.homeworkLabels = {{ homework_labels|safe }};
                window.homeworkData = {{ homework_data|safe }};

            // 数据已通过script标签直接嵌入
            // 确保变量已定义
            const attendanceLabels = window.attendanceLabels || [];
            const presentData = window.presentData || [];
            const absentData = window.absentData || [];
            const homeworkLabels = window.homeworkLabels || [];
            const homeworkData = window.homeworkData || [];

            // 检查数据是否为空
            if (attendanceLabels.length === 0 || presentData.length === 0 || absentData.length === 0) {
                console.warn('考勤数据为空，可能没有足够的考勤记录');
                // 为考勤图表提供默认数据
                if (attendanceLabels.length === 0) {
                    attendanceLabels.push('暂无数据');
                    presentData.push(0);
                    absentData.push(0);
                }
            }

            if (homeworkLabels.length === 0 || homeworkData.length === 0) {
                console.warn('作业数据为空，可能没有未提交的作业');
                // 为作业图表提供默认数据
                if (homeworkLabels.length === 0) {
                    homeworkLabels.push('暂无数据');
                    homeworkData.push(0);
                }
            }

            // 创建考勤图表
            const attendanceCtx = $('#attendanceChart')[0].getContext('2d');
            new Chart(attendanceCtx, {
                type: 'line',
                data: {
                    labels: attendanceLabels,
                    datasets: [
                        {
                            label: '出勤人数',
                            data: presentData,
                            backgroundColor: 'rgba(25, 135, 84, 0.1)',
                            borderColor: 'rgba(25, 135, 84, 1)',
                            borderWidth: 2,
                            tension: 0.3,
                            fill: true,
                            pointBackgroundColor: 'rgba(25, 135, 84, 1)',
                            pointRadius: 4,
                            pointHoverRadius: 6
                        },
                        {
                            label: '缺勤人数',
                            data: absentData,
                            backgroundColor: 'rgba(220, 53, 69, 0.1)',
                            borderColor: 'rgba(220, 53, 69, 1)',
                            borderWidth: 2,
                            tension: 0.3,
                            fill: true,
                            pointBackgroundColor: 'rgba(220, 53, 69, 1)',
                            pointRadius: 4,
                            pointHoverRadius: 6
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    interaction: {
                        intersect: false,
                        mode: 'index',
                    },
                    plugins: {
                        legend: {
                            position: 'top',
                            labels: {
                                boxWidth: 12,
                                usePointStyle: true
                            }
                        },
                        tooltip: {
                            backgroundColor: 'rgba(0, 0, 0, 0.7)',
                            padding: 12,
                            cornerRadius: 8
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            grid: {
                                color: 'rgba(0, 0, 0, 0.05)'
                            },
                            ticks: {
                                precision: 0
                            }
                        },
                        x: {
                            grid: {
                                display: false
                            }
                        }
                    },
                    animation: {
                        duration: 1000,
                        easing: 'easeOutQuart'
                    }
                }
            });
            console.log('考勤图表初始化成功');

            // 创建作业图表
            const homeworkCtx = $('#homeworkChart')[0].getContext('2d');
            new Chart(homeworkCtx, {
                type: 'bar',
                data: {
                    labels: homeworkLabels,
                    datasets: [
                        {
                            label: '未提交数量',
                            data: homeworkData,
                            backgroundColor: [
                                'rgba(54, 162, 235, 0.7)',
                                'rgba(75, 192, 192, 0.7)',
                                'rgba(153, 102, 255, 0.7)',
                                'rgba(255, 159, 64, 0.7)',
                                'rgba(255, 99, 132, 0.7)'
                            ],
                            borderColor: [
                                'rgba(54, 162, 235, 1)',
                                'rgba(75, 192, 192, 1)',
                                'rgba(153, 102, 255, 1)',
                                'rgba(255, 159, 64, 1)',
                                'rgba(255, 99, 132, 1)'
                            ],
                            borderWidth: 1,
                            borderRadius: 6
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            backgroundColor: 'rgba(0, 0, 0, 0.7)',
                            padding: 12,
                            cornerRadius: 8
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            grid: {
                                color: 'rgba(0, 0, 0, 0.05)'
                            },
                            ticks: {
                                precision: 0
                            }
                        },
                        x: {
                            grid: {
                                display: false
                            }
                        }
                    },
                    animation: {
                        duration: 1000,
                        easing: 'easeOutQuart'
                    }
                }
            });
            console.log('作业图表初始化成功');

            // 为卡片添加点击效果
            $('.card').on('click', function() {
                if (!$(this).hasClass('no-hover-effect')) {
                    $(this).addClass('shadow-lg').delay(200).queue(function() {
                        $(this).removeClass('shadow-lg').dequeue();
                    });
                }
            });

        } catch (error) {
            console.error('图表初始化失败:', error);
            // 显示友好的错误提示
            const errorMessage = `图表加载失败: ${error.message || '未知错误'}`;
            $('.card-body:has(canvas)').html(`<div class="text-center text-danger py-5"><i class="bi bi-exclamation-triangle fs-3 mb-2"></i><p>${errorMessage}</p><p class="mt-2">请刷新页面重试</p></div>`);
        }
    });
</script>

{% endblock extra_js %}